package com.shaoshaohuo.app.ui;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.liam.imageload.LoadUtils;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.shaoshaohuo.app.R;
import com.shaoshaohuo.app.SshApplication;
import com.shaoshaohuo.app.constant.AppConfig;
import com.shaoshaohuo.app.entity.BaseEntity;
import com.shaoshaohuo.app.entity.BaseHomeCouponEntity;
import com.shaoshaohuo.app.entity.BaseUserInfo;
import com.shaoshaohuo.app.entity.HomeCouponEntity;
import com.shaoshaohuo.app.entity.HomeCouponTowEntity;
import com.shaoshaohuo.app.entity.UserSignEntity;
import com.shaoshaohuo.app.entity.UserSignPointEntity;
import com.shaoshaohuo.app.framework.AccountManager;
import com.shaoshaohuo.app.framework.ActivityCollector;
import com.shaoshaohuo.app.framework.SharedPreferencesHelper;
import com.shaoshaohuo.app.framework.SharedPreferencesHelper.Field;
import com.shaoshaohuo.app.net.HttpConfig;
import com.shaoshaohuo.app.net.HttpRequest.RequestListener;
import com.shaoshaohuo.app.net.RequestParam;
import com.shaoshaohuo.app.net.RequestService;
import com.shaoshaohuo.app.ui.ec.BusinessRecordActivity;
import com.shaoshaohuo.app.ui.ec.PurchaseOrderActivity;
import com.shaoshaohuo.app.ui.ec.PurchaseRecordActivity;
import com.shaoshaohuo.app.ui.ec.SupplyOrderActivity;
import com.shaoshaohuo.app.ui.ec.SupplyRecordActivity;
import com.shaoshaohuo.app.ui.fragment.CarFragment;
import com.shaoshaohuo.app.ui.fragment.CarParentFragment;
import com.shaoshaohuo.app.ui.fragment.EcCartFragment;
import com.shaoshaohuo.app.ui.fragment.EcMainFragment;
import com.shaoshaohuo.app.ui.fragment.EcMainFragmentWithBottonNavigation;
import com.shaoshaohuo.app.ui.shipper.MyOrderShipperActivity;
import com.shaoshaohuo.app.utils.ImageLoadUtil;
import com.shaoshaohuo.app.utils.Okhttputils;
import com.shaoshaohuo.app.utils.TimeUtil;
import com.shaoshaohuo.app.utils.ToastUtil;
import com.shaoshaohuo.app.versionupdatelibrary.entity.VersionUpdateConfig;
import com.shaoshaohuo.app.view.CouPons;
import com.shaoshaohuo.app.view.UpdateDialog;
import com.squareup.picasso.Picasso;
import com.ta.utdid2.android.utils.SystemUtils;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

import static com.shaoshaohuo.app.constant.RoleTypes.ROLE_CAR;
import static com.shaoshaohuo.app.constant.RoleTypes.ROLE_EC;

/**
 *
 */
public class MainTabActivity extends BaseActivity implements OnClickListener, UpdateDialog.callBack {

//    private CanvasTransformer mTransformer;

    private View mSidingView;
    private ImageView mHeadImage;

    private View mMyInfoLayout;
    private TextView mNameText;
    private TextView mPhoneText;

    private View mOrderStatusLayout;
    private View mSettingLayout;
    private View mCaigouLayout;
    private View mGongyingLayout;

    //    private SlidingMenu slidingMenu;
    private Handler nHandler = new Handler();

    private boolean isCheckUpdate = false;

    private Fragment mContentLayout;
    private Fragment mCarFragment;
    private Fragment mUserFragment;
    private EcMainFragmentWithBottonNavigation mEcFragment;
    private Fragment mNoLoginFragment;

    private Fragment mContent;
    private boolean isFirst = true;

    private int currentState = -1;
    private View mMyPriceLayout;
    private View mPublishManagerLayout;
    private View mMyOrdersLayout;
    private long starttime;
    private RelativeLayout layout_content;
    private String activityid;
    private Intent updataService;
    private static int REQUESTPERMISSION = 110;
    private String url;
    private UpdateDialog update;
    private UpdateDialog updateDialog;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        if (savedInstanceState != null) {
//            rest
//        }
        setContentView(R.layout.activity_main_tab_layout);
        layout_content = (RelativeLayout) findViewById(R.id.layout_lin);
        starttime = SystemClock.currentThreadTimeMillis();
        initAnimation();
        initSlidingView();
        initSlidingMenu();
        initData();
        initView();
        setUpView();
        init();
        initAliasAndTags();
        initdialog();
        updateveroid();
//        changeTransltestaus(this, layout_content, TransltestausModel.NoePicter, getResources().getColor(R.color.color_FC6769));
    }

    private void updateveroid() {
        Map<String, String> headerParams = RequestParam.getHeaderParams();
        OkHttpClient okHttpClient = new OkHttpClient();
        FormBody.Builder builder = new FormBody.Builder();
//        builder.add("","")
        Request.Builder builder1 = new Request.Builder();
        Set<Map.Entry<String, String>> entriesa = headerParams.entrySet();
        for (Map.Entry<String, String> a : entriesa) {
            String key = a.getKey();
            String value = a.getValue();
            builder1.addHeader(key, value);
        }
        builder1.url(HttpConfig.BASE_HOST_URL + "/index/GetVersion").post(builder.build());
        Call call = okHttpClient.newCall(builder1.build());
        call.enqueue(new Callback() {


            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                ResponseBody body = response.body();
                String string = body.string();
                try {
                    JSONObject jsonObject = new JSONObject(string);
                    int code = jsonObject.getInt("code");
                    if (code == 0) {
                        JSONObject data = jsonObject.getJSONObject("data");
                        String version = data.getString("version");
                        PackageManager packageManager = getPackageManager();
                        PackageInfo packageInfo = packageManager.getPackageInfo(getPackageName(), 0);
                        int versionCode = packageInfo.versionCode;
                        int i = Integer.parseInt(version);
                        if (i > versionCode) {
                            //版本更新
                            url = data.getString("url");
                            final String value = data.getString("value");
                            final String s = value.replaceAll("_", "\n");
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    updateDialog = new UpdateDialog(MainTabActivity.this, url, s);
                                    setCallBack();
                                    updateDialog.show();
                                }


                            });

                        }

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (PackageManager.NameNotFoundException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void setCallBack() {
        updateDialog.setListener(this);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                           int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUESTPERMISSION) {
            if (permissions[0].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    VersionUpdateConfig.getInstance()//获取配置实例
                            .setContext(this)//设置上下文
                            .setDownLoadURL(url)//设置文件下载链接
//                                .setFileSavePath(savePath)//设置文件保存路径（可不设置）
                            .setNotificationIconRes(R.mipmap.logo)//设置通知图标
                            .setNotificationSmallIconRes(R.mipmap.logo)//设置通知小图标
                            .setNotificationTitle("版本升级")//设置通知标题
                            .startDownLoad();//开始下载
                } else {
//提示没有权限，安装不了咯
                    ToastUtil.toast("没权限无法安装");
                }
            }
        }
    }

    private void initdialog() {
        Map<String, String> headerParams = RequestParam.getHeaderParams();
        OkHttpClient okHttpClient = new OkHttpClient();
        FormBody.Builder builder = new FormBody.Builder();
//        builder.add("","")
        Request.Builder builder1 = new Request.Builder();
        Set<Map.Entry<String, String>> entriesa = headerParams.entrySet();
        for (Map.Entry<String, String> a : entriesa) {
            String key = a.getKey();
            String value = a.getValue();
            builder1.addHeader(key, value);
        }
        builder1.url(HttpConfig.BASE_HOST_URL + "/index/PushCoupon").post(builder.build());
        Call call = okHttpClient.newCall(builder1.build());
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                ResponseBody body = response.body();
                String string = body.string();
                Log.e("TAG", "onResponse: string string string string" + string);
                Gson gson = new Gson();
                BaseHomeCouponEntity baseHomeCouponEntity = gson.fromJson(string, BaseHomeCouponEntity.class);
                Log.e("TAG", "onResponse:12312123123 " + baseHomeCouponEntity.getData().getType());
                if (baseHomeCouponEntity.getData().getType().equals("1")) {
                    final HomeCouponEntity homeCouponEntity = gson.fromJson(string, HomeCouponEntity.class);
                    activityid = homeCouponEntity.getData().getData().getActivityid();

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            final CouPons couPons = new CouPons(MainTabActivity.this);
                            couPons.setpica(homeCouponEntity);
                            List<HomeCouponEntity.DataBeanXX.DataBeanX.DataBean> data = homeCouponEntity.getData().getData().getData();
                            List<View> list = new ArrayList<View>();
                            for (int i = 0; i < data.size(); i++) {
                                HomeCouponEntity.DataBeanXX.DataBeanX.DataBean dataBean = data.get(i);
                                ImageView imageView = new ImageView(MainTabActivity.this);
                                String img = dataBean.getImg();
                                Picasso.with(getApplicationContext()).load(img).into(imageView);
                                imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                                list.add(imageView);
                            }
                            couPons.activityid = activityid;
                            couPons.addyhj(list);
                            couPons.show();
                        }
                    });
                } else if (baseHomeCouponEntity.getData().getType().equals("2")) {
                    HomeCouponTowEntity homeCouponTowEntity = gson.fromJson(string, HomeCouponTowEntity.class);
//                    Log.e("TAG", "onResponse:444444444 "+homeCouponTowEntity.getData().getData().get(0) );
                    if (homeCouponTowEntity.getData().getData().size() > 0) {
                        String s = homeCouponTowEntity.getData().getData().get(0);
                        Intent intent = new Intent(MainTabActivity.this, WebTranslte.class);
                        intent.putExtra("weburl", s);
                        startActivity(intent);
                    }
                }
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        long l = SystemClock.currentThreadTimeMillis();
        Log.e("TAG", "onStart: " + (l - starttime));
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

    }

    public void toggle() {
//        slidingMenu.toggle();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isFirst) {
            isFirst = false;
        } else {
            init();
        }
        if (!isCheckUpdate) {
            checkUpdate();
        }
        MobclickAgent.onResume(this);
        boolean aBoolean = SharedPreferencesHelper.getBoolean(this, SharedPreferencesHelper.Field.HOME, false);
        if (aBoolean) {
            setcur(0);
            SharedPreferencesHelper.setBoolean(this, SharedPreferencesHelper.Field.HOME, false);
        }
        //:/ec_shoppingcart/getnum
        setnum();
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    private void init() {
        if (AccountManager.isLogin()) {
            BaseUserInfo userInfo = AccountManager.getUserInfo();
            if (userInfo != null) {
                mNameText.setText(userInfo.getRealname());
                mPhoneText.setText(userInfo.getMobile());
                mPhoneText.setVisibility(View.VISIBLE);
                String authStatus = AccountManager.getUserAuthStatus();
                if ("3".equals(authStatus)) {
                    Drawable drawable = getResources().getDrawable(R.drawable.icon_auth_yes);
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                    mNameText.setCompoundDrawables(null, null, drawable, null);
                } else {
                    Drawable drawable = getResources().getDrawable(R.drawable.icon_un_auth);
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                    mNameText.setCompoundDrawables(null, null, drawable, null);
                }
                ImageLoader.getInstance().displayImage(userInfo.getAvatar(), mHeadImage,
                        ImageLoadUtil.getDisplayImageOptions(R.drawable.icon_default_headimage, 180));

                changeState();
            }

        } else {
            mNameText.setText("未登录");
            mNameText.setCompoundDrawables(null, null, null, null);
            mPhoneText.setVisibility(View.GONE);
            LoadUtils.getInstance().loadImage(mHeadImage, R.drawable.icon_default_headimage);
            changeState();
        }
    }

    private void initAliasAndTags() {
        String mobile = AccountManager.getUserInfo().getMobile();
        String alias = SharedPreferencesHelper.getString(Field.PUSH_DEVICE_ALIAS, "");
        if (!alias.equals(mobile)) {
            Set<String> tags = new HashSet<>();
            tags.add("android");
            callBack = new JPushCallBack();
            handler = new SetAliasHandler(this, mobile, tags);
            handler.sendEmptyMessage(0);
        }
    }

    @Override
    public void backListener(String url) {
        int systemVersion = SystemUtils.getSystemVersion();
        if (systemVersion >= 6) {
            Log.e("TAG", "backListener: " + systemVersion);
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
//申请权限
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUESTPERMISSION);
                ToastUtil.toast("请允许权限进行下载安装");
//                CommonToast.showToast("请允许权限进行下载安装");
            } else {
                VersionUpdateConfig.getInstance()//获取配置实例
                        .setContext(this)//设置上下文
                        .setDownLoadURL(url)//设置文件下载链接
//                                .setFileSavePath(savePath)//设置文件保存路径（可不设置）
                        .setNotificationIconRes(R.mipmap.logo)//设置通知图标
                        .setNotificationSmallIconRes(R.mipmap.logo)//设置通知小图标
                        .setNotificationTitle("版本升级")//设置通知标题
                        .startDownLoad();//开始下载
            }
        } else {
            VersionUpdateConfig.getInstance()//获取配置实例
                    .setContext(this)//设置上下文
                    .setDownLoadURL(url)//设置文件下载链接
//                                .setFileSavePath(savePath)//设置文件保存路径（可不设置）
                    .setNotificationIconRes(R.mipmap.logo)//设置通知图标
                    .setNotificationSmallIconRes(R.mipmap.logo)//设置通知小图标
                    .setNotificationTitle("版本升级")//设置通知标题
                    .startDownLoad();//开始下载
        }
//        updataService = new Intent(SplashActivity.this, UpdataService.class);
//        updataService.putExtra("downloadurl", version.url);
//        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
////申请权限
//            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUESTPERMISSION);
////            CommonToast.showToast("请允许权限进行下载安装");
//        } else {
//            startService(updataService);
//        }
    }

    /**
     * 设置 tags handler
     *
     * @author cao
     */
    public class SetAliasHandler extends Handler {
        private Context context;
        private String mobile;
        private Set<String> tags;

        public SetAliasHandler(Context context, String mobile, Set<String> tags) {
            this.context = context;
            this.mobile = mobile;
            this.tags = tags;
        }

        @Override
        public void handleMessage(Message msg) {
            JPushInterface.setAliasAndTags(context, mobile, tags, callBack);
        }
    }

    /**
     * jpush 设置回调
     *
     * @author cao
     */
    private class JPushCallBack implements TagAliasCallback {
        @Override
        public void gotResult(int arg0, String arg1, Set<String> arg2) {
            switch (arg0) {
                case 0:
                    handler = null;
                    callBack = null;
                    SharedPreferencesHelper.setString(Field.PUSH_DEVICE_ALIAS, arg1);
                    break;
                case 6002:
                    handler.sendEmptyMessageDelayed(0, 1000 * 60);
                    break;
            }
        }

    }

    /**
     * 根据选择的不同 首页
     */
    public void changeState() {
        currentState = SshApplication.main_state;
        switch (currentState) {
            case 0:
//			mLishiShangji.setVisibility(View.GONE);
//			mQiaodaoLayout.setVisibility(View.GONE);
//			mGonghuo.setVisibility(View.GONE);
//			mCaigou.setVisibility(View.GONE);
//			mOrderStatusLayout.setVisibility(View.GONE);
//			mCaigouLayout.setVisibility(View.GONE);
//			mGongyingLayout.setVisibility(View.GONE);
//			if (mNoLoginFragment == null) {
//				String title = getIntent().getStringExtra(LogoutFragment.ARGUMENT);
//				mNoLoginFragment = LogoutFragment.newInstance(title);
//			}
//			switchContent(mNoLoginFragment);
//                startActivity(new Intent(this, SelectDisplayActivity.class));
//                finish();
                break;
            case ROLE_CAR:
                mLishiShangji.setVisibility(View.GONE);
                mQiaodaoLayout.setVisibility(View.VISIBLE);
                mSelectDisplay.setVisibility(View.VISIBLE);
                mGonghuo.setVisibility(View.GONE);
                mCaigou.setVisibility(View.GONE);
                mOrderStatusLayout.setVisibility(View.GONE);

                mCaigouLayout.setVisibility(View.GONE);
                mGongyingLayout.setVisibility(View.GONE);
                mNoLoginFragment = null;
                // }
                if (mCarFragment == null) {
                    String title = getIntent().getStringExtra(CarFragment.ARGUMENT);
                    mCarFragment = new CarParentFragment();
                }
                switchContent(mCarFragment);
                break;
            case ROLE_EC:
                mLishiShangji.setVisibility(View.VISIBLE);
                mQiaodaoLayout.setVisibility(View.VISIBLE);
                mSelectDisplay.setVisibility(View.VISIBLE);
                mGonghuo.setVisibility(View.GONE);
                mCaigou.setVisibility(View.GONE);
                mOrderStatusLayout.setVisibility(View.GONE);
                mCaigouLayout.setVisibility(View.GONE);
                mGongyingLayout.setVisibility(View.GONE);
                mNoLoginFragment = null;
                // }
                if (mEcFragment == null) {
                    String title = getIntent().getStringExtra(EcMainFragment.ARGUMENT);
                    mEcFragment = new EcMainFragmentWithBottonNavigation();
                }
                switchContent(mEcFragment);
                break;
        }
    }

    public void setcur(int dex) {
        mEcFragment.setcuritem(dex);
    }

    public void setnum() {
        Map<String, String> headerParams = RequestParam.getHeaderParams();
        Okhttputils.Instanse(this).getnet(headerParams, this, HttpConfig.BASE_HOST_URL + "/ec_shoppingcart/getnum", new Okhttputils.OkutListener() {
            @Override
            public void error(Call call, IOException e) {

            }

            @Override
            public void error(Call call, int code) {

            }

            @Override
            public void suseff(Call call, Response response, Object o) {
                NumEntity numEntity = (NumEntity) o;
                final int carNum = numEntity.getData().getCarNum();
                runhandler.post(new Runnable() {
                    @Override
                    public void run() {
                        mEcFragment.setnum(carNum);
                    }
                });
            }
        }, NumEntity.class);
    }

    private long mExitTime;

    private View mCaigou;

    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {

            if ((System.currentTimeMillis() - mExitTime) > 1000) {
                Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                mExitTime = System.currentTimeMillis();

            } else {
                ActivityCollector.finishAll();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void initSlidingView() {
        mSidingView = View.inflate(this, R.layout.view_sliding_menu, null);

        mMyInfoLayout = mSidingView.findViewById(R.id.layout_my_info);
        mHeadImage = (ImageView) mSidingView.findViewById(R.id.imageview_sidemenu_headview);
        mNameText = (TextView) mSidingView.findViewById(R.id.textview_username);
        mPhoneText = (TextView) mSidingView.findViewById(R.id.textview_phone);

        // 签到
        mQiaodaoLayout = mSidingView.findViewById(R.id.layout_sidemenu_info_qiaodao);
        mTvQiaodao = (TextView) mSidingView.findViewById(R.id.tv_qiaodao);
        icon_sign_ad = (ImageView) mSidingView.findViewById(R.id.icon_sign_ad);

        mSelectDisplay = mSidingView.findViewById(R.id.layout_select_display);
        // 供货记录
        mGonghuo = mSidingView.findViewById(R.id.layout_gonghuojilu);
        // 采购记录
        mCaigou = mSidingView.findViewById(R.id.layout_caigou);

        mLishiShangji = mSidingView.findViewById(R.id.layout_sidemenu_lishi_shangji);

        mOrderStatusLayout = mSidingView.findViewById(R.id.layout_sidemenu_order_status);
        mSettingLayout = mSidingView.findViewById(R.id.layout_sidemenu_setting);
        mCaigouLayout = mSidingView.findViewById(R.id.layout_sidemenu_order_caigou);
        mGongyingLayout = mSidingView.findViewById(R.id.layout_sidemenu_order_gongying);
        mMyPriceLayout = mSidingView.findViewById(R.id.layout_sidemenu_my_price);
        mPublishManagerLayout = mSidingView.findViewById(R.id.layout_sidemenu_publish_manager);
        mMyOrdersLayout = mSidingView.findViewById(R.id.layout_my_orders);
    }

    private void setUpView() {
        mMyInfoLayout.setOnClickListener(this);
        mQiaodaoLayout.setOnClickListener(this);
        mCaigou.setOnClickListener(this);
        mGonghuo.setOnClickListener(this);
        mSelectDisplay.setOnClickListener(this);
        mOrderStatusLayout.setOnClickListener(this);
        mSettingLayout.setOnClickListener(this);
        mCaigouLayout.setOnClickListener(this);
        mGongyingLayout.setOnClickListener(this);
        icon_sign_ad.setOnClickListener(this);
        mLishiShangji.setOnClickListener(this);
        mMyPriceLayout.setOnClickListener(this);
        mPublishManagerLayout.setOnClickListener(this);
        mMyOrdersLayout.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.layout_my_info:
                switchInfo();
                break;
            case R.id.layout_sidemenu_lishi_shangji:
                startActivity(new Intent(this, BusinessRecordActivity.class));
                break;
            case R.id.layout_sidemenu_order_status:
                if (AccountManager.isLogin()) {
                    switch (currentState) {
                        case 1:
                            startActivity(new Intent(this, MyOrderShipperActivity.class));
                            break;
                        case 2:
                            startActivity(new Intent(this, MyOrderActivity.class));
                            break;
                    }
                } else {
                    startActivity(new Intent(this, LoginActivity.class));
//                    backListener();
                }
                break;
            case R.id.layout_sidemenu_setting:
                startActivity(new Intent(this, SettingActivity.class));
                break;
            case R.id.layout_sidemenu_order_caigou:
                startActivity(new Intent(this, PurchaseOrderActivity.class));
                break;
            case R.id.layout_sidemenu_order_gongying:
                startActivity(new Intent(this, SupplyOrderActivity.class));
                break;
            case R.id.layout_sidemenu_info_qiaodao:// 跳转到 签到记录页面
                startActivity(new Intent(this, UserSignActivity.class));
                break;
            case R.id.icon_sign_ad:
                userSign();
                return;
            case R.id.layout_gonghuojilu:
                startActivity(new Intent(this, SupplyRecordActivity.class));
                break;
            case R.id.layout_select_display:
//                startActivity(new Intent(this, SelectDisplayActivity.class));
                finish();
                break;
            case R.id.layout_caigou:
                startActivity(new Intent(this, PurchaseRecordActivity.class));
                break;
            case R.id.layout_sidemenu_my_price:
                startActivity(new Intent(this, MyPriceActivity.class));
                break;
            case R.id.layout_sidemenu_publish_manager: {
//                PublishManagerActivity publishManagerFragment = PublishManagerActivity.newInstance(PublishManagerActivity.ARGUMENT_VALUE_WITH_BACK);
//                switchContent(publishManagerFragment, true);
                startActivity(new Intent(this, PublishManagerActivity.class));
            }
            break;
            case R.id.layout_my_orders: {
                startActivity(new Intent(this, OrderManagerActivity.class));
               /* switch (currentState) {
                    case ROLE_EC:
                        //TODO startActivity(new Intent(this, MyOrderShipperActivity.class));
                        break;
                    case ROLE_CAR:
                        //TODO startActivity(new Intent(this, MyOrderActivity.class));
                        CarOrderFragment orderFragment = CarOrderFragment.newInstance(CarOrderFragment.ARGUMENT_VALUE_WITH_BACK, this);
                        switchContent(orderFragment, true);
                        break;
                }*/
            }
            break;
        }

        nHandler.postDelayed(new Runnable() {

            @Override
            public void run() {
            }
        }, 500);

    }

    private void switchInfo() {
        if (currentState == 1) {
            startActivity(new Intent(this, MyInfoActivity.class));
        } else if (currentState == 2) {
            startActivity(new Intent(MainTabActivity.this, MyInfoActivity.class));
        } else {
            startActivity(new Intent(this, LoginActivity.class));
            finish();
        }


    }

    private void initData() {
        setSignPoint();
    }

    private void initView() {
        mContentLayout = (Fragment) getSupportFragmentManager().findFragmentById(R.id.layout_content);
    }

    private void switchContent(Fragment to) {
        if (mContent != null) {
            if (to != mContent) {
                FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
//                transaction.setCustomAnimations(R.anim.anim_fade_in, R.anim.anim_fade_out);
                transaction.replace(R.id.layout_content, to).commit();
                mContent = to;
            }
        } else {
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
//            transaction.setCustomAnimations(R.anim.anim_fade_in, R.anim.anim_fade_out);
            transaction.add(R.id.layout_content, to).commit(); // 隐藏当前的fragment，add下一个到Activity中
            mContent = to;
        }

    }

    private void switchContent(Fragment to, boolean isNeedBack) {
        if (mContent != null) {
            if (to != mContent) {
                FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                if (AppConfig.FRAGMENT_CUSTOM_TRANSITION_LEFT_OUT != AppConfig.FRAGMENT_NONE && AppConfig.FRAGMENT_CUSTOM_TRANSITION_RIGHT_IN != AppConfig.FRAGMENT_NONE
                        && AppConfig.FRAGMENT_CUSTOM_TRANSITION_LEFT_IN != AppConfig.FRAGMENT_NONE && AppConfig.FRAGMENT_CUSTOM_TRANSITION_RIGHT_OUT != AppConfig.FRAGMENT_NONE) {
                    transaction.setCustomAnimations(AppConfig.FRAGMENT_CUSTOM_TRANSITION_RIGHT_IN, AppConfig.FRAGMENT_CUSTOM_TRANSITION_LEFT_OUT,
                            AppConfig.FRAGMENT_CUSTOM_TRANSITION_LEFT_IN, AppConfig.FRAGMENT_CUSTOM_TRANSITION_RIGHT_OUT);
                } else {
                    transaction.setTransition(AppConfig.FRAGMENT_TRANSITION);
                }
                transaction.replace(R.id.layout_content, to);//.commit();
                if (isNeedBack) {
                    transaction.addToBackStack(null);
                }
                transaction.commit();
                mContent = to;
            }
        } else {
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            if (AppConfig.FRAGMENT_CUSTOM_TRANSITION_LEFT_OUT != AppConfig.FRAGMENT_NONE && AppConfig.FRAGMENT_CUSTOM_TRANSITION_RIGHT_IN != AppConfig.FRAGMENT_NONE
                    && AppConfig.FRAGMENT_CUSTOM_TRANSITION_LEFT_IN != AppConfig.FRAGMENT_NONE && AppConfig.FRAGMENT_CUSTOM_TRANSITION_RIGHT_OUT != AppConfig.FRAGMENT_NONE) {
                transaction.setCustomAnimations(AppConfig.FRAGMENT_CUSTOM_TRANSITION_RIGHT_IN, AppConfig.FRAGMENT_CUSTOM_TRANSITION_LEFT_OUT,
                        AppConfig.FRAGMENT_CUSTOM_TRANSITION_LEFT_IN, AppConfig.FRAGMENT_CUSTOM_TRANSITION_RIGHT_OUT);
            } else {
                transaction.setTransition(AppConfig.FRAGMENT_TRANSITION);
            }
            transaction.add(R.id.layout_content, to);//.commit(); // 隐藏当前的fragment，add下一个到Activity中
            if (isNeedBack) {
                transaction.addToBackStack(null);
            }
            transaction.commit();
            mContent = to;
        }

    }

    /**
     * 初始化滑动菜单
     */
    private void initSlidingMenu() {

        // 设置滑动菜单视图
//        setBehindContentView(R.layout.activity_main_tab);
//
//        // 设置滑动菜单的属性值
//        slidingMenu = getSlidingMenu();

//        slidingMenu.setMenu(mSidingView);
//        slidingMenu.setSlidingEnabled(true);
//        // slidingMenu.setBackgroundResource(R.color.color_323232);
//        slidingMenu.setShadowWidthRes(R.dimen.shadow_width);
//        // slidingMenu.setShadowDrawable(R.drawable.bg_loadingdialog);
//        slidingMenu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
//        slidingMenu.setFadeEnabled(true);
//        slidingMenu.setFadeDegree(0.35f);
//        slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);
//        slidingMenu.setBehindScrollScale(0.5f);
//        slidingMenu.setBehindCanvasTransformer(mTransformer);
//
//        setSlidingActionBarEnabled(true);
//
//        slidingMenu.setOnOpenListener(this);

    }

    /**
     * menu 打开时调用
     */
//    @Override
//    public void onOpen() {
//        setSignPoint();
//    }

    /**
     * 根据今天是否签到 设置 签到图标 并显示 签到获得分数
     */
    private void setSignPoint() {
        long currentTime = System.currentTimeMillis();
        long signTime = SharedPreferencesHelper.getLong(this, Field.SIGN_TIME, 0);
        if (TimeUtil.isSameDayOfMillis(currentTime, signTime)) {
            icon_sign_ad.setBackgroundResource(R.drawable.icon_signed_ad);
            icon_sign_ad.setEnabled(false);
            int point = SharedPreferencesHelper.getInt(Field.SIGN_POINT, 20);
            mTvQiaodao.setText("明日+" + point + "分");
        } else {
            RequestService.getInstance().userSignPoint(this, UserSignPointEntity.class, new RequestListener() {
                @Override
                public void onSuccess(int requestCode, BaseEntity resultData) {
                    if (resultData.isOk()) {
                        UserSignPointEntity entity = (UserSignPointEntity) resultData;
                        int isSign = entity.data.isSign;

                        int point;
                        int time = entity.data.time;

                        if (1 == isSign) {
                            point = entity.data.NextDayPoint;
                            icon_sign_ad.setBackgroundResource(R.drawable.icon_signed_ad);
                            icon_sign_ad.setEnabled(false);
                            mTvQiaodao.setText("明日+" + point + "分");
                        } else {
                            point = entity.data.point;
                            icon_sign_ad.setBackgroundResource(R.drawable.icon_sign_ad);
                            mTvQiaodao.setText("+" + point + "分");
                            icon_sign_ad.setEnabled(true);
                        }

                        SharedPreferencesHelper.setInt(Field.SIGN_POINT, point);
                        SharedPreferencesHelper.setLong(MainTabActivity.this, Field.SIGN_TIME, time);

                    }
                }

                @Override
                public void onFailed(int requestCode, Exception error, String msg) {
                }
            });
        }
    }

    /**
     * 用户签到
     */
    private void userSign() {
        RequestService.getInstance().userSign(this, UserSignEntity.class, new RequestListener() {
            @Override
            public void onSuccess(int requestCode, BaseEntity resultData) {
                if (resultData.isOk()) {
                    UserSignEntity entity = (UserSignEntity) resultData;
                    SharedPreferencesHelper.setInt(Field.SIGN_POINT, entity.data.NextDayPoint);
                    SharedPreferencesHelper.setLong(MainTabActivity.this, Field.SIGN_TIME, System.currentTimeMillis());
                    mTvQiaodao.setText("明日+" + entity.data.NextDayPoint + "分");
                    icon_sign_ad.setBackgroundResource(R.drawable.icon_signed_ad);
                    icon_sign_ad.setEnabled(false);
                }
            }

            @Override
            public void onFailed(int requestCode, Exception error, String msg) {
                showToast(msg);
            }
        });
    }

    /**
     * 初始化动画效果
     */
    private void initAnimation() {
    }

    private boolean isRequest = false;

    private View mQiaodaoLayout;

    private TextView mTvQiaodao;

    private View mGonghuo;

    private ImageView icon_sign_ad;

    private View mLishiShangji;

    private View mSelectDisplay;

    private JPushCallBack callBack;

    private SetAliasHandler handler;
    private Handler runhandler = new Handler();

    protected void checkUpdate() {
        if (isRequest) {
            return;
        }
        isRequest = true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent result) {
        super.onActivityResult(requestCode, resultCode, result);

        // 处理电商购物车fragment回调通知
        Fragment f = getSupportFragmentManager().findFragmentByTag(EcCartFragment.class.getSimpleName());
        /* 然后在碎片中调用重写的onActivityResult方法 */
        if (f != null) {
            f.onActivityResult(requestCode, resultCode, result);
        }
        Fragment carF = getSupportFragmentManager().findFragmentByTag(CarParentFragment.class.getSimpleName());
        if (carF != null) {
            carF.onActivityResult(requestCode, resultCode, result);
        }
    }

    /**
     * 核心的ac用来加载fg，所以应该来个方法，让外面调用，方便调换模式
     */
// changeTransltestaus(layout_content, this, TransltestausModel.NoePicter, getResources().getColor(R.color.color_FC6769));
    public void maintabchangeStatusBar(TransltestausModel transltestausModel, int color) {
        changeTransltestaus(this, layout_content, transltestausModel, color);
    }


}
